class PostsController < ApplicationController
	before_filter :find_user
	before_filter :find_community, :only=>[:index]
	before_filter :login_required, :except=>[:index, :show]
	before_filter :find_post, :only=>["edit", "update", "destroy", "preview"]
	layout :set_layout
	
	def index
		@posts = begin
			if !@user.nil?
				@user.posts.journal.paginate(:all, :page=>params[:page], :per_page=>20)
			elsif !@community.nil?
				@community.posts.paginate(:all, :page=>params[:page], :per_page=>20)
			end
		end || []

		respond_to do |format|
       format.html { }
       format.xml { }
       format.rss { render :layout => false }
     end
	end
	
	def show
		@post = @user.posts.find(params[:id])
		arr = @user.posts.find(:all, :select=>"id").map(&:id).map(&:to_i)
		idx = arr.index(@post.id)
		next_id = arr[idx-1]
		prev_id = arr[idx+1]
		@next_post = @user.posts.find(next_id) unless next_id.nil?
		@prev_post = @user.posts.find(prev_id) unless prev_id.nil?
		@comment = flash[:current_comment]
		comms = logged_in? && (current_user.admin? || @post.user == current_user) ? @post.comments : @post.comments.visible
		@comments = comms.roots.paginate(:page => params[:page], :per_page => 50, :order=> 'created_at ASC')
	end
	
	def new
		@post = @user.posts.new(:community_id=>params[:community_id])
	end
	
	def create
		@post = @user.posts.create!(params[:post])
		redirect_to preview_user_post_path(@user, @post)
    rescue ActiveRecord::RecordInvalid
    	render :action => 'new'
	end
	
	def update
		@post.update_attributes!(params[:post])
		redirect
    rescue ActiveRecord::RecordInvalid
    	render :action => 'edit'
	end
	
	def destroy
		@post.destroy
		redirect
	end
	
	def editall
		@posts = []
		@posts = @user.posts.journal if params[:item][:journal] == "1"
		if  params[:item][:communities] == "1" &&  params[:item][:community]
			@posts += @user.posts.find(:all, :conditions=>{:community_id => params[:item][:community]})
		end
	end
	
	protected
	
	def set_layout
		return "journal" if ['index'].include?(action_name)
		return 'application'
	end
	
	def redirect
		redirect_to user_posts_path(@user)
	end
	
	def find_user
		@user = User.find_by_login(params[:user_id]) unless params[:user_id].blank?
		@user ||= current_account
	end
	
	def find_community
		@community = Community.find(params[:community_id]) unless params[:community_id].blank?
	end
	
	def find_post
		@post = @user.posts.find(params[:id])
	end
	
	def authorized?
		logged_in? && (current_user == @user || current_user.admin?)
		#logged_in?
	end
end
